<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>111</title>
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}
			
			#container {
				width: 100vw;
				height: 100vh;
				display: flex;
				align-items: center;
				justify-content: center;
			}
			
			canvas {
				width: 500px;
				height: 500px;
				border: 1px solid magenta;
			}
		</style>
	</head>

	<body>
		<div id="container">
			<canvas id="c1" width="500px" height="500px"></canvas>
			<p id="zdgs"></p>
			<input type="button" id="zd" value="补充子弹" />
		</div>

	</body>
	<script type="text/javascript">
		window.onload = function() {
			let oCanvas = document.getElementById('c1');
			let oPen = oCanvas.getContext("2d");
			oPen.fillRect(0, 200, 100, 100);

			let a = 80;
			let i = 0;
			let t = 0;
			let g = 0;
			let q = 2;
			let o = 0;
			let zd = document.getElementById('zd');

			zd.onclick = function() {
				q = q + 5;
				console.dir(q);
				document.getElementById("zdgs").innerText = "子弹剩余：" + q
			}
			document.getElementById("zdgs").innerText = "子弹剩余：" + q
			let time
			document.onkeypress = function(e) {
				if(i == 0) {
					if(e.keyCode == 32) {

						if(o == 0 && q != 0) {
							g = g + 1;
							q--;
							o = 1;
						}

						// let time=setInterval(...)
						time = setInterval(() => {
							xxx()
						}, 500);
						// if(g==1){setInterval(()=>{xxx()},500);}

						i = 1;
						console.dir(q);
						document.getElementById("zdgs").innerText = "子弹剩余：" + q
					}
				}

			}
			oPen.fillRect(a, 240, 10, 10);

			function xxx() {
				let step = 30;
				if(i == 1) {

					if(a > 80) {
						oPen.clearRect(a, 240, 10, 10);
					}
					a = a + step;
					oPen.translate(step, 0);

					oPen.fillRect(a, 240, 10, 10);
					t = t + step
					if(a == 320) {
						clearInterval(time);
						oPen.translate(-t, 0)
						t = 0;
						a = 80;
						g = g - 1;
					}

					if(g == 0) {
						i--;
						o = 0;
					}

				}

				if(g == 0 && q == 0) {
					alert('请补充弹药');
					q = q + 5;
					document.getElementById("zdgs").innerText = "子弹剩余：" + q
				}
				console.dir(g);

			}

		}
	</script>

</html>